import React from 'react';
import { BackHandler, DeviceEventEmitter, Image, NativeModules, ScrollView, StyleSheet, Text, TextInput, TouchableOpacity, View } from 'react-native';

import DelayTouchableOpacity from '../Component/DelayTouchableOpacity'

import Constant from '../Constant/Constant'
import ScreenUtils from '../Utils/ScreenUtils'
import ColorUtils from '../Utils/ColorUtils'
import ToastUtils from '../Utils/ToastUtils'
import HttpUtils from '../Utils/HttpUtils'
import RuleUtils from '../Utils/RuleUtils'
import RouterUtils from '../Utils/RouterUtils'
import StorageUtils from '../Utils/StorageUtils'
import EncryptUtils from '../Utils/EncryptUtils'
import TimeUtils from '../Utils/TimeUtils'
import UserChangePassword from "../UserChangePassword/UserChangePassword";

export default class UserLogin extends React.Component
{
    static navigationOptions = ({navigation}) => ({
        gesturesEnabled: false,//是否支持滑动返回收拾，iOS默认支持，安卓默认关闭
        header: null,
        headerTitle: '登录',
        headerStyle: {
            backgroundColor: ColorUtils.white,
            height: ScreenUtils.statusBarHeight,
        },
        headerLeft: <View/>,
        headerRight: <View/>,
        headerTintColor: ColorUtils.black,
        headerTitleStyle: {
            fontSize: ScreenUtils.Font_18,
            color: ColorUtils.black,
            fontWeight: 'normal',
            flex: 1,
            alignSelf: 'center',
            textAlign: 'center',
        },
    });

    constructor(props)
    {
        super(props);
        this.state = {
            username: '',
            password: '',
        };
    }

    componentDidMount()
    {
        RouterUtils.pushRouter('UserLogin', this.props.navigation.state.key);
        BackHandler.addEventListener('hardwareBackPress', this.onBackLogin);
    }

    componentWillUnmount()
    {
        RouterUtils.popRouter('UserLogin', this.props.navigation.state.key);
        BackHandler.removeEventListener('hardwareBackPress', this.onBackLogin);
    }

    onBackLogin = () =>
    {
        if (this.lastBackPressed && this.lastBackPressed + 2000 >= Date.now())
        {
            BackHandler.exitApp();
            return false;
        }
        this.lastBackPressed = Date.now();
        ToastUtils.toastShortBottom('再按一次退出应用');
        return true;
    }

    jumpFindPassword()
    {
        this.props.navigation.navigate('UserFindPassword');
    }

    login()
    {
        try
        {
            RuleUtils.checkEmpty(this.state.username, '用户名不能为空');
            RuleUtils.checkPwdValid(this.state.password);
            var that = this;
            var data = {'password': EncryptUtils.md5(this.state.password), 'username': this.state.username, 'grant_type': 'password'};
            HttpUtils.login(Constant.login, data, function (resultcode, data)
            {
                StorageUtils.save('session', data.access_token);
                StorageUtils.save('username', that.state.username);
                StorageUtils.save('userId', data.user_id);
                StorageUtils.save('appmenus', data.app_menus);
                DeviceEventEmitter.emit('userReload', 'param');
                DeviceEventEmitter.emit('homeReload', 'param');
                DeviceEventEmitter.emit('appReloadInterval', 'param');
                NativeModules.DeviceNativeModule.startTrack(that.state.username, (result) =>
                {

                });
                that.props.navigation.goBack();
                if (data.default_password)
                {
                    ToastUtils.toastLongCenter('当前为初始密码，请先修改字母、数字、特殊符号组合的至少8位密码!');
                    that.props.navigation.navigate('UserChangePassword');
                }
            }, function (resultcode, reason)
            {
                ToastUtils.toastShortBottom('用户名或密码错误');
            });
        }
        catch (error)
        {
            ToastUtils.toastShortBottom(error);
        }
    }

    render()
    {
        return (
            <Image resizeMode={Image.resizeMode.stretch} source={require('../img/login_bg.png')} style={{flex: 1, width: ScreenUtils.width, height: ScreenUtils.height}}>
                <View style={{marginTop: 40, flexDirection: 'column', justifyContent: 'center', alignItems: 'center'}}>
                    <Image source={require('../img/logo.png')} style={{width: 100, height: 100}}/>
                    <Text style={{backgroundColor: 'transparent', marginTop: 16, fontSize: ScreenUtils.Font_18, color: ColorUtils.white, fontWeight: 'bold',}}>数字化城市管理无线数据采集系统</Text>
                </View>
                <View style={{borderBottomColor: ColorUtils.white, borderBottomWidth: 1, margin: 16, marginTop: 32, marginBottom: 4, flexDirection: 'column', justifyContent: 'center'}}>
                    <Text style={{backgroundColor: 'transparent', marginLeft: 8, marginTop: 4, fontSize: ScreenUtils.Font_14, color: ColorUtils.white}}>账号</Text>
                    <TextInput value={this.state.username} underlineColorAndroid='transparent' keyboardType='default' maxLength={20} placeholder='请输入用户名' placeholderTextColor={ColorUtils.light_gray} onChangeText={(text) => this.setState({username: text})} multiline={false} style={{marginTop: 4, marginLeft: 4, fontSize: ScreenUtils.Font_14, height: 40, color: ColorUtils.white,}}/>
                </View>
                <View style={{borderBottomColor: ColorUtils.white, borderBottomWidth: 1, margin: 16, marginTop: 16, marginBottom: 4, flexDirection: 'column', justifyContent: 'center'}}>
                    <Text style={{backgroundColor: 'transparent', marginLeft: 8, marginTop: 4, fontSize: ScreenUtils.Font_14, color: ColorUtils.white}}>密码</Text>
                    <TextInput value={this.state.password} underlineColorAndroid='transparent' secureTextEntry={true} keyboardType='default' maxLength={18} placeholder='请输入密码' placeholderTextColor={ColorUtils.light_gray} onChangeText={(text) => this.setState({password: text})} multiline={false}
                               style={{marginTop: 4, marginLeft: 4, fontSize: ScreenUtils.Font_14, height: 40, color: ColorUtils.white,}}/>
                </View>
                <View style={{flexDirection: 'row', justifyContent: 'space-between'}}>
                    <TouchableOpacity>
                        <View style={{marginLeft: 16, marginTop: 8, borderColor: ColorUtils.green, borderBottomWidth: 1}}>
                            <Text style={{marginBottom: 2, fontSize: ScreenUtils.Font_14, color: ColorUtils.green}}></Text>
                        </View>
                    </TouchableOpacity>
                    <TouchableOpacity onPress={() => this.jumpFindPassword()}>
                        <View style={{marginRight: 16, marginTop: 8,}}>
                            <Text style={{backgroundColor: 'transparent', marginBottom: 2, fontSize: ScreenUtils.Font_14, color: ColorUtils.white}}></Text>
                        </View>
                    </TouchableOpacity>
                </View>
                <View style={{marginTop: 30, flexDirection: 'column', justifyContent: 'center', alignItems: 'center'}}>
                    <Image resizeMode={Image.resizeMode.stretch} source={require('../img/login_bottom.png')} style={{width: ScreenUtils.width, height: 60}}/>
                </View>
                <View style={{justifyContent: 'center', alignItems: 'center', marginTop: 64}}>
                    <DelayTouchableOpacity onPress={() => this.login()}>
                        <Image source={require('../img/login_btn.png')} style={{justifyContent: 'center', alignItems: 'center', height: 46, width: ScreenUtils.width * 0.8}}>
                            <Text style={{backgroundColor: 'transparent', color: '#0E458A', fontSize: ScreenUtils.Font_16}}>
                                登录
                            </Text>
                        </Image>
                    </DelayTouchableOpacity>
                </View>
            </Image>
        );
    }
}

const styles = StyleSheet.create({});


